package vuelos;


import java.awt.BorderLayout;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;

import javax.swing.JButton;

import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class Disponibilidad extends JDialog {

	{
		//Set Look & Feel
		try {
			javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	private JLabel avLabel;
	private JButton avClose;
	private JScrollPane avPane;
	private JTable avTable;
	protected Connection link;
	private String info[];
	private VentanaEmpleado Llamador;
	private Boolean EsIda;

	public Disponibilidad(Connection c, String values[], VentanaEmpleado padre, Boolean ida) {
		// TODO Auto-generated constructor stub
		super();
		info = values;
		Llamador = padre;
		EsIda = ida;
		initGUI();
	}

	private void initGUI() {
		try {
			{
				getContentPane().setLayout(null);
				{
					avClose = new JButton();
					getContentPane().add(avClose);
					avClose.setText("Cerrar");
					avClose.setBounds(193, 271, 115, 27);
					avClose.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) {
							avCloseActionPerformed(evt);
						}
					});
				}
			}
			{
				avLabel = new JLabel();
				getContentPane().add(avLabel, "Center");
				avLabel.setText("Disponibilidad de asientos:");
				avLabel.setBounds(12, 7, 243, 22);
			}
			{
				avPane = new JScrollPane();
				this.add(avPane, BorderLayout.CENTER);
				avPane.setBounds(5, 28, 300, 237);
				{
					avTable = new JTable();
					BorderLayout idaTableLayout = new BorderLayout();
					avPane.setViewportView(avTable);
					avTable.setLayout(idaTableLayout);
					//avTable.setAutoCreateRowSorter(true);
					avTable.setBounds(39, 53, 247, 152);
					avTable.setPreferredSize(new java.awt.Dimension(297, 233));
					avTable.addMouseListener(new MouseAdapter() {
						public void mouseClicked(MouseEvent evt) {
							avTableMouseClicked(evt);
						}
					});

				}

			}
			pack();
			super.setBounds(600, 50, 315, 340);
			this.setVisible(true);

			connect();
			fillAvTable();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	private void connect(){
		if (this.link == null)
	      {
	         try
	         {
	            Class.forName("com.mysql.jdbc.Driver").newInstance();
	         }
	         catch (Exception ex)
	         {
	            System.out.println(ex.getMessage());
	         }
	         try
	         {
	        	 String servidor = "localhost:3306";
		         String baseDatos = "vuelos";
		         String usuario = "empleado";
		         String clave = "empleado";
		         String urlConexion = "jdbc:mysql://" + servidor + "/" + baseDatos;
		         this.link = DriverManager.getConnection(urlConexion, usuario, clave);
	         }
	         catch (SQLException ex)
	         {
	        	System.out.println("Problema de autenticación en la base de datos.");
	            System.out.println("SQLException: " + ex.getMessage());
	            System.out.println("SQLState: " + ex.getSQLState());
	            System.out.println("VendorError: " + ex.getErrorCode());
	         }
	      }
	}

	private void fillAvTable() {
		try
		{
		String Consulta = " SELECT vd.clase, asientos_disponibles as Disponibilidad, vd.precio as Precio " +
						  "	FROM vuelos_disponibles vd JOIN brinda " +
						  "	where brinda.vuelo = vuelo_numero AND vuelo_dia=brinda.dia " +
						  "		AND brinda.clase=vd.clase " +
						  "		AND brinda.vuelo='" + info[0].toString()+"' AND vuelo_fecha='"+info[1].toString() +"'";
		System.out.println(""+Consulta);
		Statement stmt = link.createStatement();
		ResultSet rs = stmt.executeQuery(Consulta);
		ResultSetMetaData rsmd = rs.getMetaData();
        ConsultasTableModel modelo = new ConsultasTableModel();
        for (int i = 1; i <= rsmd.getColumnCount(); i++)
         {
            String columnaNombre = rsmd.getColumnLabel(i);
            Class columnaTipo = Class.forName(rsmd.getColumnClassName(i));
            boolean columnaEditable = false;
            modelo.agregarColumna(columnaNombre, columnaTipo, columnaEditable);
         }
         avTable.setModel(modelo);

		while (rs.next())
        {
           Vector<Object> fila = new Vector<Object>();
           for (int j = 1; j <= rsmd.getColumnCount(); j++)
           {
              fila.add(rs.getObject(j));
           }
           ((ConsultasTableModel) this.avTable.getModel()).addRow(fila);
        }

		stmt.close();
		}
		catch(SQLException error)
		{
			System.out.println("Error en consulta de listado de tablas.");
		    System.out.println("SQLException: " + error.getMessage());
            System.out.println("SQLState: " + error.getSQLState());
            System.out.println("VendorError: " + error.getErrorCode());
		}
		catch (ClassNotFoundException e)
	    {
	        e.printStackTrace();
	    }

	}

	private void avCloseActionPerformed(ActionEvent evt) {
		this.setVisible(false);
		this.dispose();
		this.disconnect();
	}

	  private void disconnect()
	   {
	      if (this.link != null)
	      {
	         try
	         {
	            this.link.close();
	            this.link = null;
	         }
	         catch (SQLException ex)
	         {
	            System.out.println("SQLException: " + ex.getMessage());
	            System.out.println("SQLState: " + ex.getSQLState());
	            System.out.println("VendorError: " + ex.getErrorCode());
	         }
	      }
	   }
	  
	  private void avTableMouseClicked(MouseEvent evt) {
		  if (EsIda) { 
			  Llamador.setClaseIda(avTable.getValueAt(avTable.getSelectedRow(),0 ).toString());
			  }
		  else {
			  Llamador.setClaseVuelta(avTable.getValueAt(avTable.getSelectedRow(),0 ).toString());
		  }
	  }
}
